package utils

import (
	"BlazeRider-backend/app/models"
	"errors"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

var jwtKey = "your_jwt_secret_key" // JWT 密钥，生产环境应使用安全方式存储

// 自定义 JWT Claims
type MyClaims struct {
	RoomId       string `json:"room_id"`
	AnchorOpenId string `json:"anchor_open_id"`
	AvatarUrl    string `json:"avatar_url"`
	LiveNickName string `json:"nick_name"`
	jwt.RegisteredClaims
}

// "room_id": 7214015683695250235,
// "anchor_open_id":" "_000oJIu6APhomK7KIBGqSYm5XYPxCJB_xxx",
// "avatar_url": "https://p11.douyinpic.com/aweme/720x720/aweme-avatar/tos-cn-avt-0015_973c31e8055f78a41d3f7de3def9821d.jpeg?from=3067671334",
// "nick_name": "xxx"

// 生成 JWT Token
func GenToken(issuer string, expireHour int, liveRoomUserInfo models.LiveRoomUserInfo) (string, error) {
	mySigningKey := []byte(jwtKey)
	claims := MyClaims{
		RoomId:       liveRoomUserInfo.RoomId,
		AnchorOpenId: liveRoomUserInfo.AnchorOpenId,
		AvatarUrl:    liveRoomUserInfo.AvatarUrl,
		LiveNickName: liveRoomUserInfo.NickName,
		RegisteredClaims: jwt.RegisteredClaims{
			Issuer:    issuer,
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(expireHour) * time.Hour)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(mySigningKey)
}

// 解析 JWT Token
func ParseToken(tokenString string) (*MyClaims, error) {
	mySigningKey := []byte(jwtKey)
	token, err := jwt.ParseWithClaims(tokenString, &MyClaims{}, func(token *jwt.Token) (interface{}, error) {
		return mySigningKey, nil
	})
	if err != nil {
		return nil, err
	}
	if claims, ok := token.Claims.(*MyClaims); ok && token.Valid {
		return claims, nil
	}
	return nil, errors.New("invalid token")
}
